<template>
  <div class="user-layout absolute inset-0 flex flex-col">
    <div class="headers_connect">
      <div class="headers_lf">
        <img
          :src="$ossLink + '/app/mspbots_theme_icon/teams_command.png'"
          alt=""
        />
        <span>{{ $t('statement.um') }}</span>
        <div>
          <view-linked-info :linkKey="'UserManagement'"></view-linked-info>
        </div>
      </div>
    </div>

    <ZContainer v-loading="dataListLoading" class="user-grid">
      <BUserActions
        @batchDelete="onBatchDelete"
        @batchEnable="enabledUser"
        @batchDisabled="disabledBatchBefore"
        @batchDisabledCW="disablednonCwUser"
        @batchDisabledAutoTask="disablednonAutotaskUserFunction"
        @addUser="onOpen"
        @search="onSearch"
        @syncTeamsUser="syncTeamsUser"
        @autoMapUsers="autoMapTeamsUsers"
        @setPermission="setPermission"
        :disablednonCwUserbtn="disablednonCwUserbtn"
        :disablednonAutoTaskbtn="disablednonAutoTaskbtn"
        :dashboardUserCount="dashboardUserCount"
        :billableUserCount="billableUserCount"
        actionCls="user-grid-actions flex"
      />
      <div class="flex-1 relative user-grid-e h-0" ref="b-grid">
        <ejs-grid
          :dataSource="comDataList"
          :allowResizing="gridDefaultSetting.allowResizing"
          :allowFiltering="gridDefaultSetting.allowFiltering"
          :filterSettings="gridDefaultSetting.filterSettings"
          :allowGrouping="gridDefaultSetting.allowGrouping"
          :allowPaging="gridDefaultSetting.allowPaging"
          :toolbar="toolbar"
          :editSettings="gridDefaultSetting.editSettings"
          :allowTextWrap="gridDefaultSetting.allowTextWrap"
          :showColumnChooser="true"
          :allowReordering="gridDefaultSetting.allowReordering"
          :allowSorting="gridDefaultSetting.allowSorting"
          :sortSettings="gridDefaultSetting.initialSort"
          :allowExcelExport="gridDefaultSetting.allowExcelExport"
          :allowPdfExport="gridDefaultSetting.allowPdfExport"
          ref="datagrid"
          :toolbarClick="toolbarClick"
          height="100%"
          :selectionSettings="gridDefaultSetting.selectOptions"
          :commandClick="commandClick"
          :rowSelected="dataListSelectionChangeHandle"
          :rowDeselected="dataListSelectionChangeHandle"
          :pageSettings="gridDefaultSetting.pageSettings"
        >
          <e-columns>
            <e-column
              type="checkbox"
              :allowFiltering="false"
              :allowSorting="false"
              width="46"
            ></e-column>
            <e-column
              :template="Avatar"
              width="100"
              field="headUrl"
              headerText="Avatar"
              textAlign="Center"
            ></e-column>
            <e-column
              field="username"
              :headerText="$t('user.username')"
            ></e-column>
            <e-column
              :template="UserBtn"
              width="100"
              headerText="Action"
              :visible="$hasPermission('sys:user:update')"
              textAlign="Center"
            ></e-column>
            <e-column
              field="firstName"
              :headerText="$t('user.firstName')"
              width="120"
            ></e-column>
            <e-column
              field="lastName"
              :headerText="$t('user.lastName')"
              width="120"
            ></e-column>
            <e-column
              field="teamsMessageSwitch"
              :headerText="$t('user.message')"
              width="160"
              :template="MessageSwitchFormat"
            ></e-column>
            <e-column
              field="roleList"
              :headerText="$t('user.role')"
              width="250"
              :template="RoleFormat"
            ></e-column>
            <e-column
              field="managerName"
              :headerText="$t('user.managerName')"
              width="120"
              :template="ManagerFormat"
            ></e-column>
            <e-column
              field="status"
              :headerText="$t('user.status')"
              width="100"
              :template="StatusFormat"
            >
            </e-column>

            <e-column
              field="deptName"
              :headerText="$t('user.deptName')"
              width="120"
            >
            </e-column>
            <e-column
              field="mobile"
              :headerText="$t('user.mobile')"
              width="150"
            >
            </e-column>
            <e-column field="email" :headerText="$t('user.email')" width="200">
            </e-column>
            <e-column
              field="jobTitle"
              :headerText="$t('user.jobTitle')"
              width="200"
            >
            </e-column>
            <e-column
              field="officeLocation"
              :headerText="$t('user.officeLocation')"
              width="200"
            >
            </e-column>
            <e-column
              :template="HomeChannel"
              :headerText="$t('user.homeChannel')"
              width="200"
            >
            </e-column>
            <e-column
              :visible="connectorSetting['TEAMS']"
              field="teamsUserId"
              :headerText="$t('user.teamsUserId')"
              width="200"
            >
            </e-column>
            <e-column
              :visible="connectorSetting['CW']"
              field="cwUserName"
              :headerText="$t('user.cwUserName')"
              width="200"
            >
            </e-column>
            <e-column
              :visible="connectorSetting['TSHEET']"
              field="tsheetUserName"
              :headerText="$t('user.tsheetUserName')"
              width="230"
            >
            </e-column>
            <e-column
              :visible="connectorSetting['TD']"
              field="timedoctorUserName"
              :headerText="$t('user.timeDoctorUserName')"
              width="260"
            >
            </e-column>
            <e-column
              :visible="connectorSetting['AUTOTASK']"
              field="autoTaskUserName"
              :headerText="$t('user.autotaskUserName')"
              width="260"
            >
            </e-column>
            <e-column
              :visible="connectorSetting['SYNCROMSP']"
              field="syncroUserName"
              :headerText="$t('user.syncroUserName')"
              width="260"
            >
            </e-column>
            <e-column
              field="isGuestUser"
              :headerText="$t('user.isGuestUser')"
              width="150"
              :template="BooleanValueFormat"
            >
            </e-column>
            <e-column
              field="createDate"
              :headerText="$t('user.createDate')"
              width="180"
              :template="CreateDateFormat"
            ></e-column>
            <e-column
              field="updateDate"
              :headerText="$t('user.updateDate')"
              width="180"
              :template="UpdateDateFormat"
            ></e-column>
            <e-column
              field="lastLoginTime"
              :headerText="$t('user.lastLoginDate')"
              width="180"
              :template="LastLoginDateFormat"
            ></e-column>
          </e-columns>
        </ejs-grid>
      </div>
    </ZContainer>

    <add-or-update
      ref="addOrUpdate"
      v-if="userModalVisible"
      :connectorSetting="connectorSetting"
      :userBillableVisible.sync="userBillableVisible"
      :userBillableType.sync="userBillableType"
      :userBillable.sync="userBillable"
      :userIsWhite="userIsWhite"
      :dtoList.sync="dtoList"
      :isAlaCarte="isAlaCarte"
      :payUserRequest.sync="payUserRequest"
      @event:cancel="userModalVisible = false"
      @refreshDataList="getDataList"
    ></add-or-update>

    <el-dialog
      :title="$t('custom.apps.warning')"
      :visible.sync="dialogVisible"
      destroy-on-close
      append-to-body
      width="30%"
    >
      <span style="font-size: 14px; color: #404040; line-height: 22px">{{
        $t('user.warning')
      }}</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="dialogVisible = false">{{
          $t('cancel')
        }}</el-button>
        <el-button type="primary" size="mini" @click="disabledUser">{{
          $t('user.disable')
        }}</el-button>
        <el-button
          type="primary"
          size="mini"
          :disabled="!$hasPermission('sys:user:update')"
          @click="changeMessageStatusArr"
          >{{ $t('user.Turnusersmessageswitch') }}</el-button
        >
      </span>
    </el-dialog>
    <user-set-role
      ref="setRole"
      :visible.sync="userSetRoleVisible"
      :dtoList.sync="dtoList"
      :userBillableVisible.sync="userBillableVisible"
      :userBillableType.sync="userBillableType"
      :userBillable.sync="userBillable"
      :list="dataListSelections"
      :userIsWhite="userIsWhite"
      :isAlaCarte="isAlaCarte"
      :payUserRequest.sync="payUserRequest"
      @success="query"
    ></user-set-role>
    <user-billable
      :visible.sync="userBillableVisible"
      :dtoList.sync="dtoList"
      :type="userBillableType"
      @submit="billableSubmit"
      :totalUser="enableUser"
      @cancel="billableCancel"
    ></user-billable>
    <user-add :visible.sync="userAddVisible"></user-add>
    <el-dialog
      :visible.sync="passwordDialogVisible"
      width="480px"
      title="Create New Password"
      custom-class="reset-dialog"
      destroy-on-close
      append-to-body
    >
      <BCreatePassword
        :form="passwordResetForm"
        @cancel="passwordResetCancel"
        v-if="passwordDialogVisible"
      />
    </el-dialog>
  </div>
</template>

<script>
import Vue from 'vue'
import AddOrUpdate from './user-add-or-update'
import SelectOrganizationInput from './user-select-dept'

import BCreatePassword from '@/components/storybook/b-create-password/index'
import BHeader from '@/components/storybook/b-create-password/header'
import mixinViewModule from '@/mixins/crud-view-module'
import CreateDateFormat from '@/components/grid-format/CreateDateFormat.vue'
import UpdateDateFormat from '@/components/grid-format/UpdateDateFormat.vue'
import StatusFormat from './components/StatusFormat.vue'
import BooleanValueFormat from './components/BooleanValueFormat.vue'
import MessageSwitchFormat from './components/MessageSwitchFormat'
import Avatar from './components/Avatar'
import RoleFormat from './components/RoleFormat'
import ManagerFormat from './components/ManagerFormat'
import { BridgeUser } from './components/BridgeComponentForUser'
import LastLoginDateFormat from '@/components/grid-format/LastLoginDateFormat.vue'
import ZSPlitButton from '@/components/storybook/z-split-button/index'
import BUserActions from '@/components/storybook/b-user-actions/index'
import ZIcon from '@/components/storybook/z-icon'
import userSetRole from '@/views/modules/sys/components/user-set-role'
import userBillable from '@/views/modules/sys/components/user-billable'
import userAdd from '@/views/modules/sys/components/user-add'
import ZContainer from '@/components/storybook/z-container'
import { stringRemoveSpaceEqual } from '@/utils'
import config from "@/utils/config";

export default {
  mixins: [mixinViewModule],
  data () {
    return {
      dialogVisible: false,
      notifyLodaing: false,
      columns: 3,
      mixinViewModuleOptions: {
        getDataListURL: '/web/um/sys/user/page-obj',
        getDataListIsPage: true,
        deleteURL: '/web/um/sys/user',
        deleteIsBatch: true,
        exportURL: '/web/um/sys/user/export',
        disabledBatchURL: '/web/um/sys/user/batch/status',
        disabledIsBatch: true
      },
      includDisabled: false,
      dataForm: {
        username: '',
        deptId: '',
        gender: '',
        status: 1,
        limit: 99999
      },
      loading: false,
      gridHeight: 400,
      CreateDateFormat: function () {
        return { template: CreateDateFormat }
      },
      UpdateDateFormat: function () {
        return { template: UpdateDateFormat }
      },
      StatusFormat: function () {
        return { template: StatusFormat }
      },
      BooleanValueFormat: function () {
        return { template: BooleanValueFormat }
      },
      MessageSwitchFormat: function () {
        return { template: MessageSwitchFormat }
      },
      RoleFormat: function () {
        return { template: RoleFormat }
      },
      ManagerFormat: function () {
        return { template: ManagerFormat }
      },
      LastLoginDateFormat: function () {
        return { template: LastLoginDateFormat }
      },
      UserBtn: function () {
        return { template: UserBtn }
      },
      Avatar: function () {
        return { template: Avatar }
      },
      HomeChannel: function () {
        return { template: HomeChannel }
      },
      gridDefaultSetting: {
        allowPaging: true,
        selectOptions: {
          // checkboxOnly: true
        },
        pageSettings: {
          pageSize: 10,
          pageSizes: [10, 50, 100, 200, 1000],
          pageCount: 4
        },
        initialSort: {
          columns: [{ field: 'roleList', direction: 'Ascending' }]
        }
      },
      connectorSetting: {},
      disablednonCwUserbtn: false,
      disablednonAutoTaskbtn: false,
      toolbar: [
        // 'ExcelExport',
        'PdfExport',
        'CsvExport',
        'Search',
        'ColumnChooser'
      ],
      isChrome: navigator.userAgent.indexOf('Chrome') > -1,

      passwordResetForm: null,

      userModalVisible: false,
      userSetRoleVisible: false,
      userBillableVisible: false,
      userBillableType: null,
      userBillable: null,
      userAddVisible: false,
      dtoList: null,
      enableUser: null,
      userList: [],
      whiteList: [],
      dashboardUserCount: 0,
      billableUserCount: 0,
      queryCount: true,
      isAlaCarte: false,
      payUserRequest: false,
      payUserParams: {}
    }
  },
  watch: {
    includDisabled (val) {
      if (val) {
        this.dataForm.status = null
      } else {
        this.dataForm.status = 1
      }
      this.getDataList()
    }
  },
  computed: {
    comDataList () {
      return this.dataList.map(record => {
        return {
          ...record,
          roleIdList: (record.roleList || []).map(i => i.id),
          roleList: (record.roleList || []).map(i => i.name).join()
        }
      })
    },
    passwordDialogVisible: {
      get () {
        return !!this.passwordResetForm
      },
      set (val) {
        this.passwordResetForm = !val ? null : val
      }
    }
  },
  components: {
    userSetRole,
    userBillable,
    userAdd,
    AddOrUpdate,
    SelectOrganizationInput,
    CreateDateFormat,
    BooleanValueFormat,
    LastLoginDateFormat,
    ZSPlitButton,
    BUserActions,
    BCreatePassword,
    BHeader,
    ZContainer
  },

  created () {
    this.gridHeight = document.documentElement.clientHeight - 360
    this.getEnableUser()
    this.updateList()
    this.getConnectorStatus()
    this.getWhiteList()
    this.getBundleInfo()
    Vue['_this_user'] = this
  },
  methods: {
    async getBundleInfo () {
      let bundlesTable = {}
      const { subList } = this.$interface.pay
      const tenantCode = this.tenantCode || this.$store.state.user.tenantCode
      const { data } = await subList({ tenantCode })
      if (data.data) {
        bundlesTable = this._.find(data.data, (o) => { return o.type === 0 })
        this.isAlaCarte = !!(bundlesTable && stringRemoveSpaceEqual(bundlesTable.name, 'A la Carte'));
      }
    },
    changeMessageStatusArr () {
      this.$confirm(
        this.$t('custom.apps.deleteconfirm'),
        this.$t('custom.apps.warning'),
        {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          // type: 'warning',
          dangerouslyUseHTMLString: true
        }
      ).then(() => {
        var params = []
        this.dataListSelections.forEach(item => {
          var obj = {
            userId: item.id,
            keyword: 'teams.message.switch',
            value: false
          }
          params.push(obj)
        })
        this.$interface.system
          .postSettingUserArrApi(params)
          .then(({ data: res }) => {
            if (res.code !== 0) {
              return this.$message.error(res.msg)
            }
            this.dialogVisible = false
            this.getDataList()
            return this.$message.success(res.msg)
          })
          .catch(() => {})
      })
    },
    updateList () {
      BridgeUser.$on('updateUserList', () => {
        this.getDataList()
      })
    },
    commandClick (type, row) {
      if (type === 'Edit') {
        if (this.$store.state.user.tenantSwitch === true) {
          this.$confirm(this.$t('custom.sys.user.editText'), {
            confirmButtonText: this.$t('confirm'),
            cancelButtonText: this.$t('cancel'),
            type: 'warning'
          })
            .then(() => {
              this.addOrUpdateHandle(row.id)
            })
            .catch(() => {})
        } else {
          this.addOrUpdateHandle(row.id)
        }
      }
    },
    syncTeamsUser () {
      try {
        if (this.$store.state.user.tenantCode) {
          const params = {
            tenantId: this.$store.state.user.tenantCode,
            subjectCode: 'TEAMS',
            manualSyncPhoto: true
          }
          this.$interface.taskManager
            .syncClientData(params)
            .then(({ data: res }) => {
              if (
                res.data.sync &&
                res.data.sync.status &&
                res.data.sync.status !== 'Success'
              ) {
                return this.$message.error(
                  res.data.sync.errorMsg ? res.data.sync.errorMsg : res.msg
                )
              }

              return this.$message.success(res.msg)
            })
            .catch(() => {})
        }
      } catch (e) {}
    },
    changeDeptId (deptList) {
      deptList && deptList.length && (this.dataForm.deptId = deptList[0])
      this.query()
    },
    autoMapTeamsUsers () {
      this.notifyLodaing = true
      this.$interface.taskManager
        .putAutoMap()
        .then(({ data: res }) => {
          this.notifyLodaing = false
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.$notify({
            title: 'Synced Users',
            customClass: 'user_management_notify',
            dangerouslyUseHTMLString: true,
            message: `<div style="${
              res.data.alreadyMappingAutotaskUserCount
                ? 'display:block'
                : 'display:none'
            }">
                        <span style="display:inline-block;width:35px">${
  res.data.alreadyMappingAutotaskUserCount
}</span>Users From Autotask</div>
                      <div style="${
  res.data.alreadyMappingConnectwiseUserCount
    ? 'display:block'
    : 'display:none'
}">
                        <span style="display:inline-block;width:35px">${
  res.data.alreadyMappingConnectwiseUserCount
}</span>Users From Connectwise Manage</div>
                      <div style="${
  res.data.alreadyMappingTeamsUserCount
    ? 'display:block'
    : 'display:none'
}">
                        <span style="display:inline-block;width:35px">${
  res.data.alreadyMappingTeamsUserCount
}</span>Users From Teams</div>
                      <div style="${
  res.data.alreadyMappingTimedoctorUserCount
    ? 'display:block'
    : 'display:none'
}">
                        <span style="display:inline-block;width:35px">${
  res.data.alreadyMappingTimedoctorUserCount
}</span>Users From Timedoctor</div>
                      <div style="${
  res.data.alreadyMappingTsheetUserCount
    ? 'display:block'
    : 'display:none'
}">
                        <span style="display:inline-block;width:35px">${
  res.data.alreadyMappingTsheetUserCount
}</span>Users From TSheet</div> `,
            type: 'success'
          })
        })
        .catch(e => {
          this.notifyLodaing = false
          return this.$message.error(e.error)
        })
    },
    disablednonCwUser () {
      this.$confirm(
        this.$t('prompt.para', {
          handle: this.$t('custom.sys.user.disablednonCwUsertext')
        }),
        this.$t('prompt.title'),
        {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning'
        }
      )
        .then(async () => {
          const { disableCWUser } = this.$interface.pay
          const { data } = await disableCWUser({
            tenantCode: this.$store.state.user.tenantCode
          })
          if (data.code !== 0) {
            return this.$message.error(data.msg)
          }
          const userList = data.data.filter(item => {
            return !this.userIsWhite(item)
          })
          if (!this.isAlaCarte) {
            const { dtoList } = await this.queryNumberByUsers(userList, 2)
            this.dtoList = dtoList
            this.payUserParams = {
              bundleExtraUsersId: dtoList && dtoList.length > 0 ? dtoList[0].bundleExtraUsersId : null,
              userIdList: userList.map(item => item.id),
              type: 2
            }
          }
          if (this.dtoList && this.dtoList.length > 0) {
            this.userBillableVisible = true
            this.userBillableType = '2'
            this.userBillable = '6'
          } else {
            this.disablednonCwUserResponse()
          }
        })
        .catch(() => {})
    },
    disablednonCwUserResponse () {
      this.dataListLoading = true
      const params = {
        tenantCode: this.$store.state.user.tenantCode
      }
      this.$interface.taskManager
        .disablednonCwUser(params)
        .then(({ data: res }) => {
          this.dataListLoading = false
          if (res.code !== 0) {
            this.dataList = []
            this.total = 0
            return this.$message.error(res.msg)
          }
          if (this.payUserRequest) {
            const { payUser } = this.$interface.pay
            payUser(this.payUserParams).finally(() => {
              this.payUserRequest = false
            })
          }
          this.query()
        })
        .catch(() => {
          this.dataListLoading = false
        })
    },
    disablednonAutotaskUserFunction () {
      this.$confirm(
        this.$t('prompt.para', {
          handle: this.$t('custom.sys.user.disablednonAutotaskUsertext')
        }),
        this.$t('prompt.title'),
        {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: 'warning'
        }
      )
        .then(async () => {
          const { disableAutoTaskUser } = this.$interface.pay
          const { data } = await disableAutoTaskUser({
            tenantCode: this.$store.state.user.tenantCode
          })
          if (data.code !== 0) {
            return this.$message.error(data.msg)
          }
          const userList = data.data.filter(item => {
            return !this.userIsWhite(item)
          })
          if (!this.isAlaCarte) {
            const { dtoList } = await this.queryNumberByUsers(userList, 2)
            this.dtoList = dtoList
            this.payUserParams = {
              bundleExtraUsersId: dtoList && dtoList.length > 0 ? dtoList[0].bundleExtraUsersId : null,
              userIdList: userList.map(item => item.id),
              type: 2
            }
          }
          if (this.dtoList && this.dtoList.length > 0) {
            this.userBillableVisible = true
            this.userBillableType = '2'
            this.userBillable = '7'
          } else {
            this.disablednonAutotaskUserFunctionResponse()
          }
        })
        .catch(() => {})
    },
    disablednonAutotaskUserFunctionResponse () {
      this.dataListLoading = true
      const params = {
        tenantCode: this.$store.state.user.tenantCode
      }
      this.$interface.taskManager
        .disablednonAutotaskUserApi(params)
        .then(({ data: res }) => {
          this.dataListLoading = false
          if (res.code !== 0) {
            this.dataList = []
            this.total = 0
            return this.$message.error(res.msg)
          }
          if (this.payUserRequest) {
            const { payUser } = this.$interface.pay
            payUser(this.payUserParams).finally(() => {
              this.payUserRequest = false
            })
          }
          this.query()
        })
        .catch(() => {
          this.dataListLoading = false
        })
    },
    disabledBatchBefore () {
      this.dataListSelectionChangeHandle()
      if (
        this.dataListSelections &&
        this.dataListSelections.length &&
        this.dataListSelections.length > 0
      ) {
        let flag = false
        for (let i = 0; i < this.dataListSelections.length; i++) {
          if (
            this.dataListSelections[i][this.mixinViewModuleOptions.disabledIsBatchKey] === this.$store.state.user.id
          ) {
            flag = true
            break
          }
        }
        if (flag) {
          this.$message.error(this.$t('custom.tips.disabledSelf'))
        } else {
          var res = this.dataListSelections.some(item => {
            return (
              !item.isGuestUser && (item.cwUserName || item.autoTaskUserName)
            )
          })
          if (res) {
            this.dialogVisible = true
          } else {
            this.disabledUser()
          }
        }
      } else {
        this.$message.error(this.$t('custom.tips.selectItem'))
      }
    },
    dataListSelectionChangeHandle (arg) {
      this.dataListSelections = this.$refs.datagrid.getSelectedRecords()
    },

    getConnectorStatus () {
      const params = {
        tenantCode: this.$store.state.user.tenantCode
      }
      this.$interface.taskManager
        .getConnectorStatus(params)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          if (res.data.length > 0) {
            for (let i = 0; i < res.data.length; i++) {
              const code = res.data[i].configCode
              const status = res.data[i].status
              if (code === 'CW' && status === 1) {
                this.disablednonCwUserbtn = true
              } else if (code === 'AUTOTASK' && status === 1) {
                this.disablednonAutoTaskbtn = true
              }
            }
          }
        })
    },
    toolbarClick (args) {
      switch (args.item.text) {
        case 'PDF Export':
          this.$refs['datagrid'].pdfExport()
          break
        case 'Excel Export':
          this.$refs['datagrid'].excelExport()
          break
        case 'CSV Export':
          this.$refs['datagrid'].csvExport()
          break
      }
    },
    onOpen () {
      this.addOrUpdateVisible = true
      this.userModalVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init()
      })
    },
    onBatchDelete: async function (row) {
      const list = this.deleteRowId ? [row] : this.dataListSelections
      const userList = list.filter(item => {
        return !this.userIsWhite(item) && this._.intersection(item.roleIdList, config.freeUserRole).length === 0 && item.status !== 0
      })
      if (!this.isAlaCarte) {
        const { dtoList } = await this.queryNumberByUsers(userList, 2)
        this.dtoList = dtoList
        this.payUserParams = {
          bundleExtraUsersId: dtoList && dtoList.length > 0 ? dtoList[0].bundleExtraUsersId : null,
          userIdList: userList.map(item => item.id),
          type: 2
        }
      }
      const rows = this.$refs.datagrid.getSelectedRecords()
      if (!rows.length && !row) {
        this.$message.error(this.$t('custom.tips.selectItem'))
        return
      }
      const hasSelfUser = rows.some(i => i.id === this.$store.state.user.id)
      if (hasSelfUser) {
        this.$message.error(this.$t('custom.tips.disabledSelf'))
        return
      }
      try {
        await this.$confirm(
          'Deleted users will not be able to use MSPbots, please confirm whether to delete?',
          'Delete',
          {
            confirmButtonText: this.$t('confirm'),
            cancelButtonText: this.$t('cancel')
          }
        )
        if (this.dtoList && this.dtoList.length > 0) {
          this.userBillableVisible = true
          this.userBillableType = '2'
          this.userBillable = '3'
        } else {
          this.onBatchDeleteResponse()
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(error)
        }
      }
    },
    async onBatchDeleteResponse () {
      try {
        const rows = this.$refs.datagrid.getSelectedRecords()
        const { deleteUserInfoApi } = this.$interface.system
        const ids = rows.map(i => i.id)
        const params = {
          data: this.deleteRowId ? [this.deleteRowId] : ids
        }
        const { alaCarteUpdate } = this.$interface.pay
        alaCarteUpdate({
          userIds: ids
        })
        const { data: response } = await deleteUserInfoApi(params)
        if (response.code !== 0) {
          throw response.msg
        }
        if (this.payUserRequest) {
          const { payUser } = this.$interface.pay
          payUser(this.payUserParams).finally(() => {
            this.payUserRequest = false
          })
        }
        this.$message.success('Success')
        this.getDataList()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error(error)
        }
      }
    },
    async onDelete (row) {
      this.deleteRowId = row.id
      await this.onBatchDelete(row)
    },
    async onReset (row) {
      this.passwordResetForm = {
        userId: row.id,
        email: row.email
      }
    },
    onSearch (status) {
      this.dataForm.status = status
      this.getDataList()
    },
    passwordResetCancel () {
      this.passwordResetForm = false
    },
    getEnableUser () {
      const params = {
        status: 1
      }
      this.$interface.schedule.getUserListApi(params).then(({ data: res }) => {
        if (res.code === 0) {
          this.enableUser = res.data.total
        }
      })
    },
    setPermission () {
      if (this.dataListSelections.length > 0) {
        const useSelf = this._.find(this.dataListSelections, {
          id: this.$store.state.user.id
        })
        this.userSetRoleVisible = true
        if (useSelf) {
          setTimeout(() => {
            this.$message.warning(`You can't set your own role`)
          }, 1000)
        }
      } else {
        this.$message.warning('Please selected user')
      }
    },
    async queryNumberByUsers (userList = [], status) {
      const { queryNumberByUsers } = this.$interface.pay
      const list = userList.map(item => item.id)
      const { data } = await queryNumberByUsers({
        userIds: list,
        status: status
      })
      return data.data
    },
    async enabledUser () {
      const userList = this.dataListSelections.filter(item => {
        return !this.userIsWhite(item) && this._.intersection(item.roleIdList, config.freeUserRole).length === 0 && item.status === 0
      })
      if (!this.isAlaCarte) {
        const { dtoList } = await this.queryNumberByUsers(userList, 1)
        this.dtoList = dtoList
        this.payUserParams = {
          bundleExtraUsersId: dtoList && dtoList.length > 0 ? dtoList[0].bundleExtraUsersId : null,
          userIdList: userList.map(item => item.id),
          type: 1
        }
      }
      this.enabledBatch()
    },
    async disabledUser () {
      const userList = this.dataListSelections.filter(item => {
        return !this.userIsWhite(item) && this._.intersection(item.roleIdList, config.freeUserRole).length === 0 && item.status === 1
      })
      if (!this.isAlaCarte) {
        const { dtoList } = await this.queryNumberByUsers(userList, 2)
        this.dtoList = dtoList
        this.payUserParams = {
          bundleExtraUsersId: dtoList && dtoList.length > 0 ? dtoList[0].bundleExtraUsersId : null,
          userIdList: userList.map(item => item.id),
          type: 2
        }
      }
      this.disabledBatch()
    },
    async getManageUserList () {
      this.dashboardUserCount = this.comDataList.filter(item => {
        return this._.intersection(item.roleIdList, config.freeUserRole).length > 0 && !item.roleIdList.includes(config.attendanceOnlyId)
      }).length
    },
    async getWhiteList () {
      const { paywallFreeAccountList } = this.$interface.reports
      const { data: res } = await paywallFreeAccountList({ queryStr: '' })
      this.whiteList = this._.filter(res.data, item => {
        return (
          item.tenantCode === this.$store.state.user.tenantCode &&
          item.status === 1
        )
      })
    },
    userIsWhite (item) {
      // const isTenant = this._.find(this.whiteList, { type: 2 })
      // if (isTenant) {
      //   return true
      // }
      const whiteUser = this._.find(this.whiteList, {
        freeAccount: item.username
      })
      if (item && whiteUser) {
        if (whiteUser.type === 0) {
          if (item.username === whiteUser.freeAccount) {
            return true
          }
        }
        if (whiteUser.type === 1) {
          if (item.roleIds.includes(item.roleIds)) {
            return true
          }
        }
      }
      return false
    },
    billableSubmit (params) {
      // if (params === 'query') {
      //   return this.query()
      // }
      // this.userAddVisible = true
      this.payUserRequest = true
      switch (this.userBillable) {
        case '1':
          this.enabledBatchResponse()
          break
        case '2':
          this.disabledBatchResponse()
          break
        case '3':
          this.onBatchDeleteResponse()
          break
        case '4':
          this.$refs.addOrUpdate.dataFormSubmitResponse()
          break
        case '5':
          this.$refs.setRole.updateUserRole()
          break
        case '6':
          this.disablednonCwUserResponse()
          break
        case '7':
          this.disablednonAutotaskUserFunctionResponse()
          break
        default:
      }
    },
    billableCancel () {
      this.dtoList = null
    }
  },
  beforeDestroy () {
    BridgeUser.$off('updateUserList')
    delete Vue['_this_user']
  }
}
const UserBtn = Vue.component('user-btn', {
  components: {
    ZIcon
  },
  template: `<div style="display: flex;justify-content: flex-end;">
      <ZIcon :disabled="!$hasPermission('sys:user:update')"  @click.native="clickSelect('Edit',$data.data)" icon="cuifont icon_edit" content="Edit" size="14" hover tooltip style="margin-right:6px;font-size:12px"/>
      <ZIcon  :disabled="!$hasPermission('sys:user:reset')" icon="cuifont icon_key" size="14"  content="Reset Password" hover style="margin-right:6px" tooltip @click.native="onReset($data.data)"/>
      <ZIcon :disabled="!$hasPermission('sys:user:delete')" icon="el-icon-delete" size="14"  tooltip content="Delete" hover @click.native="onDelete($data.data)"/>
    </div>`,
  data () {
    return {}
  },
  methods: {
    clickSelect (e, row) {
      Vue._this_user.commandClick(e, row)
    },
    onDelete (row) {
      Vue._this_user.onDelete(row)
    },
    onReset (row) {
      Vue._this_user.onReset(row)
    }
  }
})
const HomeChannel = Vue.component('home-channel', {
  template: `<div v-if="$data.data.homeChannel">{{$data.data.homeChannel}}</div><div v-else><el-link :underline="false" style="font-weight: bold;" type="danger" @click="clickSelect('Edit',$data.data)">Add home channel</el-link></div>`,
  data () {
    return {}
  },
  methods: {
    clickSelect (e, row) {
      Vue._this_user.commandClick(e, row)
    }
  }
})
</script>
<style lang="scss" scoped>
.user-grid {
  &-actions {
    border-bottom: 1px solid #dde1e6;
    padding-bottom: 16px;
  }
  &-e {
    margin-top: 16px;
  }
}
.headers_connect {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  height: 48px;
  background: #ffffff;
  box-shadow: 0px 0px 8px 0px #f0f0f0;
  border-radius: 4px;
  border: 1px solid rgba(0, 0, 0, 0.01);
  margin-bottom: 10px;
  .headers_lf {
    display: flex;
    align-items: center;
    font-size: 20px;
    font-weight: 600;
    color: rgba(0, 0, 0, 0.75);
  }
  .headers_rg {
    .cuifont {
      font-size: 14px;
      cursor: pointer;
    }
  }
  img {
    width: 20px;
    height: 20px;
    margin-right: 10px;
  }
}
</style>
<style lang="scss">
.reset-dialog {
  .el-dialog__header {
    border-bottom: 1px solid rgba(0, 0, 0, 0.06);
    padding: 13px 19px;
    font-weight: 600;
    color: rgba(0, 0, 0, 0.9);
  }
  .el-dialog__body {
    padding: 0;
  }
}

.user_management_notify {
  width: 350px !important;
}
</style>
